<script lang="js" setup name="MainToolbar">
import { ref, reactive, computed, onMounted, onUnmounted } from "vue";
import { useRouter } from "vue-router";
import ToolbarButton from "@/components/ToolbarButton.vue";
import LayoutWnd from "../components/LayoutWnd.vue";
import tbButtons from "../actions/tbButtons.js";
import { useAppStore } from "../stores/appStore.js";
import { storeToRefs } from "pinia";

const appStore = useAppStore();
const router = useRouter();
const { layout } = storeToRefs(appStore);
const layoutWnd = ref(null);
const layoutWndPos = reactive({ x: 0, y: 0 });
const emit = defineEmits(["action"]);
const btnRefs = reactive({});
const isMobile = ref(false);

// 全局菜单状态管理
const activeMenuButton = ref(null);
const menuRefs = reactive({});

// 检测移动端设备
const checkMobile = () => {
    isMobile.value = window.innerWidth <= 768 ||
        /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
};

const getBtnRef = (el, name) => {
    if (el) {
        btnRefs[name] = el;
        menuRefs[name] = el;
    }
};

// 菜单管理方法
const showMenu = (buttonName, menuData, position) => {
    // 关闭当前活动的菜单（如果有）
    if (activeMenuButton.value && activeMenuButton.value !== buttonName) {
        hideMenu();
    }

    activeMenuButton.value = buttonName;

    // 显示菜单
    if (btnRefs[buttonName] && btnRefs[buttonName].showMenu) {
        btnRefs[buttonName].showMenu(menuData, position);
    }
};

const hideMenu = () => {
    if (activeMenuButton.value && btnRefs[activeMenuButton.value]) {
        btnRefs[activeMenuButton.value].hideMenu();
    }
    activeMenuButton.value = null;
};

const isMenuActive = (buttonName) => {
    return activeMenuButton.value === buttonName;
};

// 菜单事件处理
const onShowMenu = (event) => {
    const { buttonName, menuData, position } = event;

    // 关闭当前活动的菜单（如果有）
    if (activeMenuButton.value && activeMenuButton.value !== buttonName) {
        hideMenu();
    }

    activeMenuButton.value = buttonName;

    // 直接调用按钮的showMenu方法
    if (btnRefs[buttonName] && btnRefs[buttonName].showMenu) {
        btnRefs[buttonName].showMenu(menuData, position);
    }
};

const onHideMenu = (event) => {
    const { buttonName } = event;

    if (activeMenuButton.value === buttonName) {
        activeMenuButton.value = null;
    }
};

const mouseButtons = ["tbbScroll", "tbbMove", "tbbZoom"];

// 移动端优化的按钮列表
const tb2dButtons = computed(() => {
    const allButtons = tbButtons.filter(btn => btn.owner.includes("2d"));

    // 过滤掉不需要的按钮：工具调窗、测量、文字、旋转
    const filteredButtons = allButtons.filter(btn => {
        const excludedButtons = [
            "tbbWindow",     // 工具调窗
            "tbbMeasure",    // 测量
            "tbbText",       // 文字
            "tbbFlip",       // 旋转/翻转
            "tbbWWWL"        // 窗宽窗位预设
        ];
        return !excludedButtons.includes(btn.name);
    });

    // 移动端显示更简洁的按钮集合
    if (isMobile.value) {
        return filteredButtons.filter(btn => {
            // 保留核心功能按钮
            const essentialButtons = [
                "tbbLoadFolder", "tbbLoadPacs", "tbbLayout", "tbbScroll",
                "tbbMove", "tbbZoom", "tbbReset", "tbbPseudoColor", "tbbBack"
            ];
            return essentialButtons.includes(btn.name);
        });
    }

    return filteredButtons;
});

const initMouseButtons = () => {
    btnRefs.tbbScroll.setMouse(appStore.toolBindings.scroll);
    btnRefs.tbbMove.setMouse(appStore.toolBindings.pan);
    btnRefs.tbbZoom.setMouse(appStore.toolBindings.zoom);
};

const updateToolBindings = () => {
    appStore.toolBindings.scroll = btnRefs.tbbScroll.getMouse();
    appStore.toolBindings.pan = btnRefs.tbbMove.getMouse();
    appStore.toolBindings.zoom = btnRefs.tbbZoom.getMouse();

    // 调试：输出当前的绑定状态
    console.log("updateToolBindings 被调用");
    console.log("scroll:", appStore.toolBindings.scroll);
    console.log("pan:", appStore.toolBindings.pan);
    console.log("zoom:", appStore.toolBindings.zoom);
};

const layoutStyle = computed(() => {
    return {
        top: `${layoutWndPos.y}px`,
        left: `${layoutWndPos.x}px`
    };
});

const showLayoutWnd = (rect) => {
    layoutWndPos.x = rect.x;
    layoutWndPos.y = rect.y + rect.height;
    layoutWnd.value.show();
};
const onLayout = (r, c) => {
	console.log("onLayout", r, c);
	// layout.row = r;
	// layout.col = c;
    // emit("layout", { row: r, col: c });
    emit("action", { name: "layout", row: r, col: c });
};


const onAction = (action, evt, rect) => {
    console.log("onAction被调用:", action, evt, rect);
    console.log("action.id:", action.id);
    console.log("action.name:", action.name);
    console.log("btnRefs状态:", Object.keys(btnRefs));

    // 检测是否为触摸事件（移动端）
    const isTouchEvent = evt && evt.type && evt.type.includes('touch');

    if (evt && !isTouchEvent) {
        // 鼠标事件处理
        console.log("buttons:", evt.buttons, action.name);
        if (mouseButtons.includes(action.name)) {
            mouseButtons.forEach(btnName => {
                if (btnName !== action.name) {
                    if (btnRefs[btnName]) {
                        btnRefs[btnName].updateMouse(0, evt.buttons);
                    } else {
                        console.warn(`按钮引用不存在: ${btnName}`);
                    }
                } else {
                    if (btnRefs[btnName]) {
                        btnRefs[btnName].updateMouse(evt.buttons, 0);
                    } else {
                        console.warn(`按钮引用不存在: ${btnName}`);
                    }
                }
            });

            updateToolBindings();
        }
    } else {
        // 触摸事件或没有事件对象（移动端触摸点击处理）
        if (mouseButtons.includes(action.name)) {
            console.log("移动端工具切换:", action.name);
            // 移动端特殊处理：确保工具状态正确
            mouseButtons.forEach(btnName => {
                if (btnName !== action.name) {
                    if (btnRefs[btnName]) {
                        btnRefs[btnName].updateMouse(0, 7); // 清除所有按钮状态
                        console.log(`禁用按钮: ${btnName}`);
                    } else {
                        console.warn(`按钮引用不存在: ${btnName}`);
                    }
                } else {
                    if (btnRefs[btnName]) {
                        // 移动端：切换按钮状态，而不是固定为左键
                        const currentState = btnRefs[btnName].getMouse();
                        const newState = currentState === 1 ? 0 : 1; // 切换状态
                        btnRefs[btnName].updateMouse(newState, 6); // 设置新状态，清除其他
                        console.log(`切换按钮 ${btnName} 状态: ${currentState} -> ${newState}`);
                    } else {
                        console.warn(`按钮引用不存在: ${btnName}`);
                    }
                }
            });

            updateToolBindings();

            // 强制更新工具绑定状态，确保移动端工具切换生效
            setTimeout(() => {
                updateToolBindings();
                console.log("移动端工具绑定状态强制更新");
            }, 50);
        }
    }

    switch (action.id) {
        case "load-folder":
            emit("action", { name: "openFolder" });
            break;
        case "load-pacs":
            emit("action", { name: "openPacs" });
            break;
        case "layout":
            console.log("Layout button clicked, showing layout window");
            showLayoutWnd(rect);
            break;
        case "crossline":
            emit ("action", { name: "crossline", checked: action.checked });
            break;
        case "pseudo1":
        case "pseudo2":
        case "pseudo3":
        case "pseudo4":
        case "pseudo5":
        case "pseudo6":
        case "ClearPseudoColor":
            emit("action", { name: "colorMap", value: action.data });
            break;
        case "reset":
            emit ("action", { name: "resetCamera" });
            break;
        case "theme":
            if (appStore.theme === "light") {
                appStore.theme = "dark";
            } else {
                appStore.theme = "light";
            }
            break;
        case "navbar":
            emit("action", { name: "changeNavPos"});
            break;
        case "toolbar":
            break;
        case "threed":
            emit ("action", { name: "mprvr" });
            break;
        case "back-home":
            // 返回首页
            router.push({ path: "/" });
            break;
    }
};

// 处理窗口大小变化
const handleResize = () => {
    checkMobile();
};

onMounted(() => {
	// console.log("MainToolbar mounted:");
	checkMobile();
	initMouseButtons();
	window.addEventListener('resize', handleResize);

	// 延迟确保按钮引用正确设置
	setTimeout(() => {
		// 确保滚动工具默认激活
		if (btnRefs.tbbScroll) {
			btnRefs.tbbScroll.updateMouse(1, 6); // 左键激活，其他禁用
			updateToolBindings();
			console.log("默认激活滚动工具");
		} else {
			console.warn("tbbScroll按钮引用未找到，重新初始化");
			// 重新初始化鼠标按钮
			setTimeout(() => {
				initMouseButtons();
				if (btnRefs.tbbScroll) {
					btnRefs.tbbScroll.updateMouse(1, 6);
					updateToolBindings();
					console.log("重新初始化后激活滚动工具");
				}
			}, 100);
		}
	}, 100);
});

onUnmounted(() => {
    window.removeEventListener('resize', handleResize);
});
</script>

<template>
	<div class="toolbar">
		<LayoutWnd ref="layoutWnd" :style="layoutStyle" @layout="onLayout" />
		<ToolbarButton
			v-for="btn in tb2dButtons"
			:key="btn.id"
			:btnInfo="btn"
			:ref="el => getBtnRef(el, btn.name)"
			@action="onAction"
			@showMenu="onShowMenu"
			@hideMenu="onHideMenu"
		/>
	</div>
</template>

<style lang="scss" scoped>
.toolbar {
	display: flex;
	flex-direction: row;
	align-items: center;
	width: 100%;
	padding: 2px;
	flex-wrap: wrap; /* 允许换行 */
	overflow-y: auto; /* 垂直滚动 */
	overflow-x: hidden; /* 隐藏水平滚动 */
	border-bottom: 1px solid grey;
	height: auto; /* 自适应高度 */
	min-height: 46px; /* 最小高度 */

	/* 移动端优化 */
	touch-action: manipulation;
	-webkit-overflow-scrolling: touch; /* iOS 平滑滚动 */
	scrollbar-width: none; /* Firefox 隐藏滚动条 */
	-ms-overflow-style: none; /* IE/Edge 隐藏滚动条 */
}

/* 隐藏滚动条 */
.toolbar::-webkit-scrollbar {
	display: none;
}

/* 超小屏幕手机 (320px - 480px) */
@media (max-width: 480px) {
	.toolbar {
		padding: 2px 1px;
		min-height: 46px;
		max-height: none; /* 移除最大高度限制 */
		height: auto; /* 自适应高度 */
		align-items: flex-start;
		justify-content: flex-start;
		flex-wrap: wrap;
		gap: 1px;

		/* 移动端触摸优化 */
		-webkit-tap-highlight-color: transparent;
		touch-action: pan-y pinch-zoom;

		/* 移动端按钮样式优化 */
		:deep(.tbbutton) {
			min-width: 44px;
			min-height: 44px;
			flex-shrink: 0;
			border-radius: 6px;
			padding: 0 8px;
			margin: 1px;
		}

		:deep(.tbbutton-drop) {
			min-width: 52px;
			min-height: 44px;
			flex-shrink: 0;
			border-radius: 6px;
			padding: 0;
			margin: 1px;
		}

		/* 移动端图标大小调整 */
		:deep(.svg-icon) {
			width: 20px !important;
			height: 20px !important;
		}
	}
}

/* 小屏幕手机 (481px - 768px) */
@media (min-width: 481px) and (max-width: 768px) {
	.toolbar {
		padding: 3px 2px;
		min-height: 50px;
		max-height: none; /* 移除最大高度限制 */
		height: auto; /* 自适应高度 */
		align-items: flex-start;
		justify-content: flex-start;
		flex-wrap: wrap;
		gap: 2px;

		/* 移动端按钮样式优化 */
		:deep(.tbbutton) {
			min-width: 48px;
			min-height: 48px;
			flex-shrink: 0;
			padding: 0 10px;
			margin: 1px;
		}

		:deep(.tbbutton-drop) {
			min-width: 60px;
			min-height: 48px;
			flex-shrink: 0;
			padding: 0;
			margin: 1px;
		}
	}
}

/* 平板设备适配 (769px - 1024px) */
@media (min-width: 769px) and (max-width: 1024px) {
	.toolbar {
		height: auto; /* 自适应高度 */
		min-height: 55px;
		padding: 3px;

		:deep(.tbbutton) {
			min-width: 52px;
			min-height: 48px;
		}

		:deep(.tbbutton-drop) {
			min-width: 68px;
			min-height: 48px;
		}
	}
}

/* 大屏幕平板/小桌面 (1025px - 1366px) */
@media (min-width: 1025px) and (max-width: 1366px) {
	.toolbar {
		height: auto; /* 自适应高度 */
		min-height: 60px;
		padding: 4px;

		:deep(.tbbutton) {
			min-width: 58px;
			min-height: 52px;
		}

		:deep(.tbbutton-drop) {
			min-width: 74px;
			min-height: 52px;
		}
	}
}

/* 大桌面设备 (1367px+) */
@media (min-width: 1367px) {
	.toolbar {
		height: auto; /* 自适应高度 */
		min-height: 65px;
		padding: 5px;

		:deep(.tbbutton) {
			min-width: 64px;
			min-height: 60px;
		}

		:deep(.tbbutton-drop) {
			min-width: 84px;
			min-height: 60px;
		}
	}
}
</style>
